<?php
/**
 * dbfront
 * (c) 2010-2013 Stephen Adkins <spadkins@gmail.com>
 * This software began development in 2010.
 * It is based on code dating from 1999.
 *
 * License: GPL 2.0
 * The contents of this file may be used under the terms of
 * the GNU General Public License Version 2 or later (the "GPL").
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 * */

# Get rid of this error using the following PHPUnit comments.
#     PDOException: You cannot serialize or unserialize PDO instances
/**
 * @backupGlobals          disabled
 * @backupStaticAttributes disabled
 */

class TestOptionsTest extends PHPUnit_Framework_TestCase {
    private static $ua, $fh, $http_user_agent, $client_connection_token, $username, $password, $email, $password_hash, $session_expire_dttm, $auth_token;
    public static function setUpBeforeClass () {
        global $context, $options;

        self::$email    = 'scott9876@mailinator.com';
        self::$password = 'tiger';
        self::$username = 'scott';
        self::$http_user_agent = 'PHP/curl (phpunit) Internal Test Suite';
        self::$client_connection_token = '29426efc143b2d5511f46e38c358e92f0d313cf8d39bc9abe23547ad0caad6a8';

        # These variables are necessary for computing the client_connection_token
        $_SERVER['REMOTE_ADDR']     = '127.0.0.1';
        $_SERVER['HTTP_USER_AGENT'] = self::$http_user_agent;

        self::$ua = curl_init();

        $result = curl_setopt(self::$ua, CURLOPT_USERAGENT, self::$http_user_agent);
        $result = curl_setopt(self::$ua, CURLOPT_RETURNTRANSFER, true);

        $prefix = $options['prefix'];
        if ($prefix[0] !== '/') {
            $prefix = getcwd() . '/' . $prefix;
        }
        $result = curl_setopt(self::$ua, CURLOPT_COOKIE, "appdata=$prefix");

        self::$fh = fopen("out/TestOptionsTest.out", "w");
    }
    public function setUp () {}

    public static function tearDownAfterClass () {
        global $context, $options;
        fclose(self::$fh);
    }
    public function tearDown () {}

    /** 
     * @group   min
     */
    public function testTestOptions () {
        global $context, $options;
        $url = $options['apps_urldir'] . '/sitefront/front-framework/test_options.php';
        $response = $this->getHttpPageVariables($url);

        # [options_file] => /mnt/xvdf/id/prod/apps/sitefront/front-framework-test/appdata/test01/etc/options.ini
        # [appdata] => /mnt/xvdf/id/prod/apps/sitefront/front-framework-test/appdata/test01
        # [prefix] => /mnt/xvdf/id/prod/apps/sitefront/front-framework-test/appdata/test01
        $option_vars_w_cwd = array(
            'options_file', 'appdata', 'prefix'
        );
        $cwd = getcwd();
        foreach ($option_vars_w_cwd as $var) {
            $this->assertEquals($response[$var], $cwd.'/'.$options[$var], "Compare ($var) remote option ($response[$var]) to local option ($options[$var])");
        }

        $option_vars = array(
            'site_name', 'http_host', 'app_env', 'apps_dir', 'apps_urldir',
            'test_mode', 'test_mode_allow_http', 'signup_mode',
            'recaptcha_disable', 'recaptcha_auto_validate', 'recaptcha_public_key', 'recaptcha_private_key',
            'server_secret', 'app.title', 'app.namespace', 'db.refresh_metadata_mins', 'db.sqlite.timeout', 'include_path',
            'ext_urldir', 'ext_jsfile', 'debug_file', 'debug_file_mode',
            'trace', 'trace_width', 'debug', 'debug_options', 'debug_sql',
            'site_baseurl', 'script_symlink_dir',
            'version', 'version_urldir',
            'global_cookie_domain', 'site', 'site_short', 'site6',
            'abs_include_path', 'favicon', 'lang', 'locale', 'timezone', 'theme'
        );
        foreach ($option_vars as $var) {
            $this->assertEquals($response[$var], $options[$var], "Compare ($var) remote option ($response[$var]) to local option ($options[$var])");
        }
        # THESE DON'T WORK YET
        # 'adj_script_name_dir', 'adj_script_name', 'adj_script_filename_dir', 'adj_script_filename', 'real_version', 'version_dir', 
        return($response);
    }

    private function getHttpPageVariables ($url) {
        global $options;
        fwrite(self::$fh, "##########################################################################\n");
        fwrite(self::$fh, "# URL:  $url\n");
        fwrite(self::$fh, "##########################################################################\n");
        #$success = curl_setopt(self::$ua, CURLOPT_VERBOSE, true);
        $success = curl_setopt(self::$ua, CURLOPT_URL, $url);
        if (!$success) throw new \Exception('Web agent prep failed (CURLOPT_URL)');
        $html = curl_exec(self::$ua);
        if (!$html) throw new \Exception('Web agent exec failed (GET)');
        $response = $this->page_decode($html);
        fwrite(self::$fh, "OUTPUTS:\n");
        fwrite(self::$fh, print_r($response,true));
        return($response);
    }

    private function page_decode ($html) {
        $matches = array();
        $response = array();
        $lines = explode("\n",$html);
        foreach ($lines as $line) {
            if (preg_match('/^([^ ]+) += +\[([^\[\]]*)\] *$/', $line, $matches)) {
                $response[$matches[1]] = $matches[2];
            }
        }
        return($response);
    }
}

